import React from "react";

export const NavigationContext = React.createContext();
export const LocationContext = React.createContext();

/**
 *
 * @param {*} children:需要渲染的子节点，location:路径，navigator:导航相关属性
 */
export function Router({ children, navigator, location }) {
  return (
    <NavigationContext.Provider value={{ navigator }}>
      <LocationContext.Provider value={{ location }}>
        {children}
      </LocationContext.Provider>
    </NavigationContext.Provider>
  );
}

export function Routes({ children }) {
  return useRoutes(createRoutesFromChildren(children));
}

export function useLocation() {
  return React.useContext(LocationContext).location;
}

export function Route() {
  return null;
}

export function useRoutes(routes) {
  const location = useLocation();
  const pathname = location.pathname;

  for (let i = 0; i < routes.length; i++) {
    const { path, element } = routes[i];
    const match = matchPatch(path, pathname);

    if (match) {
      return element;
    }
  }
}

export function matchPatch(path, pathname) {
  const matcher = compilePath(path);
  const match = pathname.match(matcher);
  if (!match) return null;
  return match;
}

export function compilePath(path) {
  const regexpSource = "^" + path + "$";
  const matcher = new RegExp(regexpSource);
  return matcher;
}

export function createRoutesFromChildren(children) {
  const routes = [];

  React.Children.forEach(children, (child) => {
    // 拿到 Route 标签上的相关属性
    const route = {
      path: child.props.path,
      element: child.props.element,
    };
    routes.push(route);
  });

  return routes;
}
